﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

using MGAS.Model.Entity;

namespace MGAS.Model
{
    class SensorMetaDataCollector : ISensorMetaDataCollector
    {
        public event EventHandler<EventArgs> PollingMetaDone;
        public event EventHandler<EventArgs> PollingProgress;

        private Communicator _com;
        private Dictionary<byte, ISensorData> _data;
        public SensorMetaDataCollector()
        {
            _com = new Communicator();
            _data = new Dictionary<byte, ISensorData>();
        }

        private Thread _tWork;
        private byte _progress;
        public void StartPollingMeta()
        {
            _com.Open();
            _tWork = new Thread(Work);
            _tWork.Name = "PollingWorker";
            _tWork.Start();
        }

        public IEnumerable<ISensorData> GetMetaInfos()
        {
            if (_progress == byte.MaxValue)
                return _data.Values;
            else
                throw new InvalidOperationException("Not finish polling yet.");
        }

        public byte Progress
        {
            get { return _progress; }
        }

        private void Work()
        {
            var list = Enumerable.Range(0, 256);
            foreach (var i in list)
            {
                _progress = (byte)i;
                if (_progress % 5 == 0 && PollingProgress != null)
                    PollingProgress(this, EventArgs.Empty);

                var metadata = _com.Query(_progress, true);
                _data[_progress] = metadata;
            }
            _com.Close();
            if (PollingMetaDone != null)
                PollingMetaDone(this, EventArgs.Empty);
        }
    }
}
